package com.phonetools.commonutils.number

/**
 * 字符串转Int，转换失败时返回指定的[defVal]
 * @param  defVal 默认值
 * @return Int
 */
fun String.toIntOrDef(defVal: Int = 0): Int {
    if (this.trim().isEmpty()) return defVal
    return try {
        this.toInt()
    } catch (e: Exception) {
        e.printStackTrace()
        defVal
    }
}

/**
 * 字符串转Double，转换失败时返回指定的[defVal]
 * @param  defVal 默认值
 * @return Double
 */
fun String.toDoubleOrDef(defVal: Double = 0.00): Double {
    if (this.trim().isEmpty()) return defVal
    return try {
        this.toDouble()
    } catch (e: Exception) {
        e.printStackTrace()
        defVal
    }
}

/**
 * 字符串转Float，转换失败时返回指定的[defVal]
 * @param  defVal 默认值
 * @return Float
 */
fun String.toFloatOrDef(defVal: Float = 0.0f): Float {
    if (this.trim().isEmpty()) return defVal
    return try {
        this.toFloat()
    } catch (e: Exception) {
        e.printStackTrace()
        defVal
    }
}